/*
 * @lc app=leetcode.cn id=106 lang=java
 *
 * [106] 从中序与后序遍历序列构造二叉树
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 * int val;
 * TreeNode left;
 * TreeNode right;
 * TreeNode() {}
 * TreeNode(int val) { this.val = val; }
 * TreeNode(int val, TreeNode left, TreeNode right) {
 * this.val = val;
 * this.left = left;
 * this.right = right;
 * }
 * }
 */
class Solution {
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        return build(inorder, 0, inorder.length - 1,
                postorder, 0, postorder.length - 1);
    }

    public TreeNode build(int[] inorder, int inStart, int inEnd,
            int[] postorder, int postStart, int postEnd) {
        if (inStart > inEnd) {
            return null;
        }
        int rootVal = postorder[postEnd];
        int rightSize = 0;
        for (int i = inEnd; i >= inStart; i--) {
            if (inorder[i] == rootVal) {
                break;
            }
            rightSize++;
        }
        TreeNode root = new TreeNode(rootVal);
        root.left = build(inorder, inStart, inEnd - rightSize - 1,
                postorder, postStart, postEnd - rightSize - 1);
        root.right = build(inorder, inEnd - rightSize + 1, inEnd,
                postorder, postEnd - rightSize, postEnd - 1);
        return root;
    }
}
// @lc code=end
